package com.open.ssm.mqtt.sub;

import java.io.UnsupportedEncodingException;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** 
 * 订阅消息的回调类 
 * 
 * 必须实现MqttCallback的接口并实现对应的相关接口方法CallBack 类将实现 MqttCallBack。 
 * 每个客户机标识都需要一个回调实例。在此示例中，构造函数传递客户机标识以另存为实例数据。 
 * 在回调中，将它用来标识已经启动了该回调的哪个实例。 
 * 必须在回调类中实现三个方法： 
 * 
 *  public void messageArrived(MqttTopic topic, MqttMessage message)接收已经预订的发布。 
 * 
 *  public void connectionLost(Throwable cause)在断开连接时调用。 
 * 
 *  public void deliveryComplete(MqttDeliveryToken token)) 
 *  接收到已经发布的 QoS 1 或 QoS 2 消息的传递令牌时调用。 
 *  由 MqttClient.connect 激活此回调。 
 * 
 */  
public class SubTopicFromCmdResCallback implements MqttCallback {
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	/**
	 * This method is called when the connection to the server is lost.
	 *
	 * @param cause the reason behind the loss of connection.
	 */
	public void connectionLost(Throwable cause) {
		logger.info("订阅者SubTopicFromCmdRes-->connectionLost连接断开.....");
		// 监测到MQTT客户端连接断开，主动释放MQTT客户端资源
		SubTopicFromCmdRes.getInstance().close();
		logger.error(cause.getMessage(), cause);
	}  
	/**
	 * This method is called when a message arrives from the server.
	 */	
	public void deliveryComplete(IMqttDeliveryToken token) {
	    logger.info("订阅者SubTopicFromCmdRes-->deliveryComplete:" + token.isComplete());  
	}
	
	/**
	 * This method is called when a message arrives from the server.
	 */
	public void messageArrived(String topic, MqttMessage message)  {
		try {
			logger.info("订阅者SubTopicFromCmdRes-->messageArrived收到topic:{}", topic); 
			String recMsg = new String(message.getPayload(),"UTF-8");
			logger.info("订阅者SubTopicFromCmdRes-->messageArrived收到数据:{}",recMsg);
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
}  

